package com.hospital.gateway.module.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

import com.hospital.common.utils.PropertiesLoader;

/**
 * 网关跨域配置
 * @author yhn
 * @version 1.0
 */
@Configuration
public class GatewayCorsConfig {
    
    @Bean
    public CorsWebFilter corsWebFilter() {
        // 获取配置信息
        Properties corsProperties = PropertiesLoader.load("cors.properties");
        
        CorsConfiguration config = new CorsConfiguration();
        // 放行哪些原始域
        config.setAllowedOriginPatterns(Arrays.asList(corsProperties.getProperty("cors.allowOrigins").split(",")));
        // 放行哪些请求方式
        config.setAllowedMethods(Arrays.asList(corsProperties.getProperty("cors.allowMethods").split(",")));
        // 放行哪些原始请求头部信息
        config.setAllowedHeaders(Arrays.asList(corsProperties.getProperty("cors.allowHeaders").split(",")));
        // 暴露哪些头部信息
        config.setExposedHeaders(Arrays.asList(corsProperties.getProperty("cors.exposedHeaders").split(",")));
        // 是否允许证书
        config.setAllowCredentials(true);
        // 设置预检请求的缓存时间（秒）
        config.setMaxAge(Duration.ofSeconds(Long.parseLong(corsProperties.getProperty("cors.maxAge"))));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}